<template>
	<view class="p-2">
		<view class="p-2 border-bottom flex align-stretch">
			<view class="flex justify-center align-center font-weight-bold mr-2">
				+86
			</view>
			<input class="flex-1" type="text" v-model="phone" placeholder="手机号验证码登录" />
		</view>
		<view class="p-2 flex align-stretch border-bottom">
			<input type="text" placeholder="请输入验证码" v-model="code" class="flex-1" />
			<view class="flex justify-center align-center" @click="getCode"
				:class="codetime > 0 ? 'text-light-muted':'text-main'">
				{{codetime > 0 ? codetime + ' s' : '获取验证码'}}
			</view>
		</view>
		<view class="pt-4 px-2">
			<button :class="isDisable ? 'bg-main-disabled':'bg-main'" class=" text-white  text-center" 
			style="border-radius: 50rpx;" :disabled="isDisable"
			@click="submit">
				完成
			</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				phone: '',
				code: '',
				codetime: 0, //验证码倒计时
			}
		},
		computed:{
			isDisable() {
				if (this.phone === '' || this.code === '') {
					return true
				}
				return false
			},
		},
		methods: {
			isCheck() {
				let rules =/^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/
				if (!rules.test(this.phone)) {
					uni.showToast({
						title: '手机号码格式不正确',
						icon: 'none'
					});
					return false
				}
				return true
			},
			//获取验证码
			getCode() {
				if (this.codetime > 0) {
					return
				}
				if (!this.isCheck()) return;
				this.$H.post('/user/sendcode', {
					phone: this.phone
				}, {
					nactive: true
				}).then(res => {
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					});
					this.codetime = 60
					let timer = setInterval(() => {
						if (this.codetime >= 1) {
							this.codetime--
						} else {
							this.codetime = 0
							clearInterval(timer)
						}
			
					}, 1000)
				})
			},
			submit() {
				if (!this.isCheck()) {
					return
				}
				this.$H.post('/user/bindphone',{
					phone:this.phone,
					code:this.code
				},{
					token:true
				}).then( res => {
					console.log(res)
					//将绑定的手机号码存入vuex
					if(!res) return
					this.$store.commit('editUserInfo',{
						key:'phone',
						value:this.phone
					})
					uni.navigateBack({
						delta: 1
					});
					uni.showToast({
						title: '绑定成功',
						icon:'none'
					});
				})
			}
		}
	}
</script>

<style>

</style>
